package com.cssw.fyzb.busi.api.user;

import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.core.model.dodb.User;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.cssw.fyzb.busi.cache.CacheKeys.forVerify;
import static com.cssw.fyzb.busi.util.Bizs.ERROR_VERIFY;
import static com.cssw.fyzb.busi.util.Bizs.UNKNOWN_USER;

/**
 * 新增用户
 *
 * @author Feng Chen
 */
@Function(description = "重新绑定设备", parameters = {
        @Parameter(name = "mobile", type = Type.String, description = "手机号码", required = true),
        @Parameter(name = "code", type = Type.String, description = "短信验证码", required = true),
        @Parameter(name = "imsi", type = Type.String, description = "设备编号", required = true),
})
@Component
public class RebindDevice implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private SimpleCache simpleCache;

    private static final Logger logger = LoggerFactory.getLogger(RebindDevice.class);

    @Override
    public Response execute(Request request) throws Exception {
        String mobile = request.getString("mobile");
        String code = request.getString("code");
        String imsi = request.getString("imsi");
        try {
            String cache = simpleCache.get(forVerify(mobile));
            if (cache == null || !code.equals(cache)) {
                return Response.fail(ERROR_VERIFY.message, ERROR_VERIFY.code);
            }
            User user = userService.getByMobile(mobile);
            if (user != null) {
                userService.updateImsi(user.getUserId(), imsi);
                return Response.success();
            }
            // 删除内存中的验证码
            simpleCache.delete(forVerify(mobile));
            return Response.fail(UNKNOWN_USER.message, UNKNOWN_USER.code);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("重新绑定设备失败");
        }
    }

}
